<template>
	<div class="content">
		<div id="meta2d"></div>
	</div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted } from 'vue';
import { Meta2d, register, registerAnchors, registerCanvasDraw } from '@meta2d/core';
import { flowPens, flowAnchors } from '@meta2d/flow-diagram';
import { activityDiagram, activityDiagramByCtx } from '@meta2d/activity-diagram';
import { classPens } from '@meta2d/class-diagram';
import { sequencePens, sequencePensbyCtx } from '@meta2d/sequence-diagram';
import { register as registerEcharts } from '@meta2d/chart-diagram';
import { registerHighcharts } from '@meta2d/chart-diagram';
import { registerLightningChart } from '@meta2d/chart-diagram';
import { formPens, formPath2DPens } from '@meta2d/form-diagram';
import { chartsPens } from '@meta2d/le5le-charts';
import { ftaPens, ftaPensbyCtx, ftaAnchors } from '@meta2d/fta-diagram';
import { useRoute } from 'vue-router';
// import { serviceInvoke } from '/@/api/access/device';
import { Session } from '/@/utils/storage';
import moment from 'moment';
import mittBus from '/@/utils/mitt';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { validateNull } from '/@/utils/validate';

const route = useRoute();

let meta2d: any = null;
let token: string;
// 定义父组件传过来的值
const props = defineProps({
	meta2dUrl: {
		type: String,
		default: '',
	},
	met2dId: {
		type: String,
		default: '',
	},
});

// 检测页面是否处于全屏模式
const isPageFullscreen = () => {
	return !!(document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement);
};

// document.addEventListener('fullscreenchange', () => {
// 	if(isPageFullscreen()){
// 		meta2d.fitView(true, 20);
// 		meta2d.render(true);
// 	}

// })

watch(
	() => props.meta2dUrl,
	(val) => {
		if (val) {
			open();
		}
	},
	{
		immediate: true,
	}
);

onMounted(async () => {
	token = Session.getToken();
	initMeta2d();
	meta2d.on('SHOWSTATUSDB', (e) => {
		let params: any = {
			unitNo: e.params,
			msgType: 'SHOWSTATUSDB',
		};
		mittBus.emit('openShowStatusDb', params);
	});

	meta2d.on('SHOWSTATUSSB', (e) => {
		let params: any = {
			unitNo: e.params,
			msgType: 'SHOWSTATUSSB',
		};
		mittBus.emit('openShowStatusDb', params);
	});
	meta2d.on('SWITCH_ONOFF', (e) => {
		console.log(JSON.parse(e.params));
		let obj = JSON.parse(e.params);
		// serviceInvoke({
		// 	unitNo: obj?.unit_no,
		// 	service: obj?.service_name,
		// 	args: {
		// 		circuit_id: obj.circuit_id,
		// 		switch_onoff: obj.switch_onoff,
		// 	},
		// 	timestamp: moment().valueOf(),
		// }).then((res) => {
		// 	if (res.ok) {
		// 		useMessage().success('操作成功');
		// 	} else {
		// 		useMessage().error(err.msg);
		// 	}
		// });
	});
	// 视频
	meta2d.on('SHOWVIDEO', (e) => {
		// console.log(e,"eeeeeeee");
		let params: any = {
			msgType: 'SHOWVIDEO',
			dataObj: e,
		};
		mittBus.emit('openShowVideo', params);
	});
	//热泵主机弹窗
	meta2d.on('SHOWSTATUSRSB', (e) => {
		let params: any = JSON.parse(e.params);
		mittBus.emit('openShowStatusRSB', params);
	});
});

const initMeta2d = () => {
	const options = {
		// width: 1920,
		// height: 1080,
		// background: '#1e2430',
		// color: '#bdc7db',
		background: 'transparent',
		// color: '#000',
		width: undefined,
		height: undefined,
	};

	meta2d = new Meta2d('meta2d', options);
	//注册基本图形库
	registerBasicDiagram();
	meta2d.on('opened', opened);
	// open();

	//注册企业图形库
	setTimeout(async () => {
		(globalThis as any).userId = meta2d.store.data.userId;
		// (globalThis as any).registerIot((globalThis as any).userId,'/js/2d-components.js');
		if ((globalThis as any).meta2dTools && (globalThis as any).registerToolsNew) {
			(globalThis as any).registerToolsNew();
		}
	}, 1000);
};

const opened = () => {
	// if(route.query.id&&(route.query.id as string).startsWith('2d')){
	meta2d.fitView(true, 0); //充满屏幕
	// }else{
	//   meta2d.fitSizeView(true, 0); //大屏充满屏幕
	// }
};

const open = () => {
	// let url = '/json/2d.json';

	let url = 'http://' + props.meta2dUrl;
	// if((route.query.id as string).startsWith('2d')){
	//   meta2d.setOptions({
	//     background: '#fff',
	//     color: '#000',
	//     width:undefined,
	//     height:undefined
	//   });
	// }

	_fetch(url, function (text: any) {
		let data = JSON.parse(text);
		if (validateNull(data.https)) {
			data['https'] = [
				{
					http: `/api/admin/scadaModel/data?id=` + props.met2dId,
					method: 'GET', //设置请求方式 版本1.0.26以上支持
					httpTimeInterval: 5000, // 轮询间隔时间, 默认 1000
					httpHeaders: {
						Authorization: 'Bearer ' + token, // token
					},
				},
			];
		} else {
			data.https[0].http = `/api/admin/scadaModel/data?id=` + props.met2dId;

			data.https[0].method = 'GET'; //设置请求方式 版本1.0.26以上支持
			data.https[0].httpTimeInterval = 5000; // 轮询间隔时间, 默认 1000
			data.https[0].httpHeaders = {
				Authorization: 'Bearer ' + token, // token
			};
		}

		data.locked = 1;
		data.rule = false;
		(globalThis as any).userId = data.userId;
		meta2d.open(data);
		meta2d.fitView(true, 50);
	});
};

function _fetch(url: any, cb: any) {
	var xhr = new XMLHttpRequest();
	xhr.open('GET', url, true);
	xhr.send();
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4 && xhr.status == 200) {
			cb && cb(xhr.responseText);
		}
	};
}

//参考文档:https://doc.le5le.com/document/119754049
function registerBasicDiagram() {
	register(flowPens());
	registerAnchors(flowAnchors());
	register(activityDiagram());
	registerCanvasDraw(activityDiagramByCtx());
	register(classPens());
	register(sequencePens());
	registerCanvasDraw(sequencePensbyCtx());
	registerEcharts();
	registerHighcharts();
	registerLightningChart();
	register(formPath2DPens());
	registerCanvasDraw(formPens());
	registerCanvasDraw(chartsPens());
	register(ftaPens());
	registerCanvasDraw(ftaPensbyCtx());
	registerAnchors(ftaAnchors());
}

onUnmounted(() => {
	meta2d?.off('opened', opened);
	meta2d?.destroy();
});

const resize = () => {
	let width = window.innerWidth;
	let height = window.innerHeight;
	meta2d.resize(width, height);
	meta2d.fitView(); //居中/适应窗口大小等操作
};

// 暴露变量
defineExpose({
	resize,
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.content {
	width: 100%;
	position: relative;
	/* background-color: #1e2430; */
	height: calc(100vh - 140px);
}

#meta2d {
	position: absolute !important;
	width: 100%;
	height: 100%;
	touch-action: none;
	overflow: hidden;
}
</style>
